﻿using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace SyncCuringData
{
    partial class SyncCuringDataService : ServiceBase
    {
        private IScheduler scheduler;

        private string cron = "0 0 8,18 1/1 * ? ";

        public SyncCuringDataService()
        {
            InitializeComponent();
            // 创建作业调度器
            ISchedulerFactory factory = new StdSchedulerFactory();
            scheduler = factory.GetScheduler().Result;
        }

        private void RunScheduler()
        {
            // 启动调度器
            scheduler.Start();
            // 创建作业
            IJobDetail job = JobBuilder.Create<CuringJob>()
                .WithIdentity("CuringJob", "CuringJobGroup")
                .Build();
            /*
            //// 创建触发器，每10s执行一次 简单触发器
            //ITrigger trigger = TriggerBuilder.Create()
            //    .WithIdentity("CuringTrigger", "CuringJobGroup")
            //    .StartNow()
            //    .WithSimpleSchedule(x => x
            //        .WithIntervalInSeconds(10)
            //        .RepeatForever())
            //    .Build();
            */
            //创建触发器
            ITrigger trigger = TriggerBuilder.Create()
               .WithIdentity("CuringTrigger", "CuringJobGroup")
               .StartNow().WithCronSchedule(cron)
               .Build();
            // 加入到作业调度器中
            scheduler.ScheduleJob(job, trigger);
        }
        protected override void OnStart(string[] args)
        {
            // TODO: 在此处添加代码以启动服务。
            LogHelper.Info("调度器状态：" + scheduler.IsStarted.ToString());
            if (!scheduler.IsStarted)
            {
                LogHelper.Info("调度器启动");
                RunScheduler();
            }
        }

        protected override void OnStop()
        {
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
            if (!scheduler.IsShutdown)
            {
                scheduler.Shutdown();
            }
        }
    }
}
